<template>
  <div id="app">
    <v-header></v-header>
    <user-sider v-show="usersidebar"></user-sider>
    <div class="top">
      <div style="color: #FFF;padding-top: 20px">
        <p style="font-size: 36px;font-weight: bold;letter-spacing: 2px">100</p>
        <span style="font-size: 14px;color: #CCC">服务分</span>
      </div>
      <div style="color: #FFF;width: 200px;margin: 0 auto;padding-top: 20px">
        <div style="float: left">
          <p style="font-size: 20px;font-weight: bold;letter-spacing: 2px">26</p>
          <span style="font-size: 14px;color: #CCC">今日接单</span>
        </div>
        <div style="float: left;margin-left: 42px;color: #CCC">|</div>
        <div style="float:right;">
          <p style="font-size: 20px;font-weight: bold;letter-spacing: 2px">356</p>
          <span style="font-size: 14px;color: #CCC">今日收入</span>
        </div>
      </div>
    </div>
    <div class="content">
      <template v-for="(item,index) in msgList">
        <transition
          name="bounce"
          enter-active-class="bounceIn"
          leave-active-class="bounceOut">
          <div class="item" v-show="item.flag">
            <p style="font-size: 16px;margin-bottom: 5px">有新的订单啦~</p>
            <p class="lines">起点：{{item.startAddress}}</p>
            <p class="lines">终点：{{item.endAddress}}</p>
            <p class="lines">总路程：{{distanceByLnglat(item.startLongitude, item.startLatitude, item.endLongitude, item.endLatitude)}} 公里</p>
            <p class="lines">距您：{{distanceByLnglat(driverLongitude, driverLatitude, item.startLongitude, item.startLatitude)}} 公里</p>
            <div class="go" @click="go(index, item.orderNumber)">立即出发</div>
          </div>
        </transition>
      </template>
    </div>
    <div class="bottom">
      <div class="go">出车</div>
    </div>
    <!--    <router-view></router-view>-->
    <!--    <v-mask v-show="ismask" ></v-mask>-->
    <!--    <v-footer></v-footer>-->
    <!--    <suggest v-if="suggest"></suggest>-->
  </div>
</template>

<script>
import vHeader from './header.vue'
import vMask from '../Mask.vue'
import suggest from '../suggest/suggest.vue'
import userSider from '../userSidebar/sideBar.vue'
import { mapActions, mapState } from 'vuex'
import 'vue2-animate/dist/vue2-animate.min.css'
import {Indicator} from "mint-ui";
import {grabOrder, receiving} from "../../api";

// import vFooter from '@/components/footer.vue'
// import mapState from 'vuex'
export default {
  data() {
    return{
      msgList: [],
      driverLatitude: '',
      driverLongitude: '',
      webSocket: ''
    }
  },
  computed: {
    ...mapState([
      'usersidebar',
      'checkTelephone',
      'ismask',
      'suggest',
      'hasLocation'
    ])
  },
  created() {
    let _this = this
    if(navigator.geolocation) {
      var id = navigator.geolocation.watchPosition(function(position){
        _this.driverLatitude = position.coords.latitude
        _this.driverLongitude = position.coords.longitude
      }, function(err){
        switch(err.code) {
          case err.PERMISSION_DENIED: return "PERMISSION_DENIED";
          case err.POSITION_UNAVAILABLE: return "POSITION_UNAVAILABLE";
          case err.TIMEOUT: return "TIMEOUT";
          default: return "UNKNOWN_ERROR";
        }
      })
      // navigator.geolocation.clearWatch(id); 停止监视
    }else {
      console.log("你的浏览器不支持geolocation");
    }
  },
  watch: {
    msgList() {
      let _this = this
      setTimeout(() => {
        _this.msgList[_this.msgList.length - 1].flag = true
      }, 1000)
    }
  },
  methods: {
    ...mapActions([
      'get_telephone'
    ]),
    distanceByLnglat: function (startLng, startLat, endLng, endLat) {
      function Rad(d) {
        return d * Math.PI / 180.0;
      }
      let radLat1 = Rad(startLat);
      let radLat2 = Rad(endLat);
      let a = radLat1 - radLat2;
      let b = Rad(startLng) - Rad(endLng);
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
      s = Math.round(s * 10000) / 10000;
      return Math.round(s / 1000)
    },
    go: function (index, orderNumber) {
      let _this = this
      let params = new URLSearchParams()
      params.append('driverId', _this.$store.state.driverInfo.id)
      params.append('orderNumber', orderNumber)
      params.append('driverToken', _this.$store.state.driverInfo.token)
      grabOrder(params)
      .then(res => {
        // 抢单成功，去接乘客
        _this.$store.state.order = _this.msgList[index]
        _this.$store.state.order.driverId = _this.$store.state.driverInfo.id
        _this.$store.state.order.driverPhone = _this.$store.state.driverInfo.phone

        let toUser = _this.$store.state.order.passengerToken
        _this.webSocket.send('{"to":"' + toUser + '","identity":"' + "driver" +
          '","msg": "' + _this.$store.state.order.orderNumber +
          '","userLongitude":"' + _this.$store.state.position.lng +
          '","userLatitude":"' + _this.$store.state.position.lat + '"}');

        _this.$router.push({ path: '/driver/goPassenger' })
      })
      .catch(err => {
        console.log(err)
      })
    }
  },

  components: {
    vHeader,
    vMask,
    suggest,
    userSider
  },
  mounted() {
    let _this = this

    var map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 13
    });
    AMap.plugin('AMap.Geolocation', function() {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：5s
        buttonPosition:'RB',    //定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showCircle: false
        // zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition(function(status,result){
        if(status=='complete'){
          onComplete(result)
        }else{
          onError(result)
        }
      });
    });

    //解析定位结果
    function onComplete(data) {
      console.log(data)
      if(_this.$store.state.startLocation == null) {
        _this.$store.state.startLocation = data.position
      }
      _this.$store.state.position = data.position
      _this.$store.state.formattedAddress = data.formattedAddress
      _this.$store.state.address.start = data.formattedAddress
      _this.$store.state.addressComponent = data.addressComponent
      _this.$store.state.addressComponent.city = data.addressComponent.city.slice(0,data.addressComponent.city.length-1)
    }
    //解析定位错误信息
    function onError(data) {
      console.log("定位失败:" + data.message)
    }

    this.webSocket = new WebSocket('ws://192.168.137.1:8813/websocket/' + _this.$store.state.driverInfo.token);

    this.webSocket.onerror = function (event) {
      onError(event)
    };

    this.webSocket.onopen = function (event) {
      onOpen(event)
    };

    this.webSocket.onmessage = function (event) {
      onMessage(event)
    };

    function onMessage(event) {
      // let _this = this
      var msg = JSON.parse(event.data)
      if (msg && msg.ping && msg.ping != '') {
        _this.webSocket.send('{"pong":"' + msg.ping +
          '","identity":"' + "driver" +
          '","token":"' +  _this.$store.state.driverInfo.token +
          '","userLongitude":"' + _this.$store.state.position.lng +
          '","userLatitude":"' + _this.$store.state.position.lat + '"}');
      } else {
        msg.msg.flag = false
        console.log(msg)
        _this.msgList.push(msg.msg)
      }
    }

    function onOpen(event) {
      console.log('Connection established')
    }

    function onError(event) {
      alert(event.data);
    }
  },
  destroyed() {
    this.webSocket.close()
  }
}
</script>
<style scoped>
#app{
  background-color: #f6f6f6;
}
.top{
  margin-top: 55px;
  width: 100%;
  height: 200px;
  background-color: #444;
}
.content{
  position: relative;
  padding-top: 10px;
  top: -50px;
  width: 100%;
  padding-bottom: 100px;
}
.content .item{
  position: relative;
  margin: 0 auto;
  margin-bottom: 10px;
  width: 83%;
  padding: 10px 15px 10px 15px;
  background-color: #FFF;
  border: solid 2px #e8e8e8;
  box-shadow: 0px 0px 10px rgba(52, 52, 52, 0.1);
}
.content .item .lines{
  font-size: 14px;
  line-height: 24px;
}
.content .item .go{
  font-size: 14px;
  padding: 5px 10px 5px 10px;
  width: 58px;
  background-color: #ff6f1c;
  border-radius: 5px;
  color: #FFF;
  position: absolute;
  bottom: 10px;
  right: 20px;
  box-shadow: 0px 0px 10px rgba(50, 50, 50, .2);
}
.bottom{
  width: 100%;
  height: 70px;
  background-color: #444;
  position: fixed;
  bottom: 0px;
}
.bottom .go{
  margin: 0 auto;
  margin-top: 8px;
  width: 55px;
  height: 55px;
  background-color: #ff6f1c;
  border-radius: 55px;
  color: #FFF;
  line-height: 55px;
}
</style>
